import asyncio    
from fastapi import FastAPI, WebSocket
from app.core.config import settings
from app.api import market, order, sector, backtest          # 新增
from app.services.sector_crawler import crawl_sector_1m, create_sector_table
from app.services.backtest import create_bt_tables,run_backtest
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from datetime import date, timedelta
import uvicorn

app = FastAPI(title="QBot-GNN API", version="0.0.1")

app.include_router(market.router)   # 注册行情路由
app.include_router(order.router)    # 注册订单路由
app.include_router(sector.router)   # 挂载板块路由
app.include_router(backtest.router) # 挂载回测路由

    
@app.on_event("startup")
async def init():
    create_sector_table()
    create_bt_tables()
    scheduler = AsyncIOScheduler()
    scheduler.add_job(crawl_sector_1m, 'interval', minutes=5, max_instances=1)
    scheduler.start()
    asyncio.create_task(market.latest_tick())
    sched = AsyncIOScheduler()
    sched.add_job(
        lambda: run_backtest(
            name='DailyGridGNN',
            codes=['sz000001', 'sz000002', 'sh600519'],
            start=date.today() - timedelta(days=365),
            end=date.today()
        ),
        'cron', hour=15, minute=30, timezone='Asia/Shanghai'
    )
    sched.start()
    
@app.get("/api/healthz")
def healthz():
    return {"status": "ok", "version": "0.0.1"}

@app.websocket("/ws/tick")
async def tick_ws(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"echo: {data}")

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
